import { h, render } from "vue"
import confirmComponent from "./index.vue"

/**
 * 确认框
 * 用户只传入一个参数时，默认是内容，标题为空
 * @param {*} title 标题
 * @param {*} content 内容
 * @param {*} cancelText 取消按钮文字
 * @param {*} confirmText 确认按钮文字
*/
export const confirm = (title = '标题', content = '', cancelText = '取消', confirmText = '确定') => {
  return new Promise((resolve, reject) => {
    if (title && !content) {
      content = title
      title = ''
    }

    /**
     * 关闭回调
     */
    const close = () => {
      // 把渲染的render函数移除
      render(null, document.body)
    }

    /**
     * 取消回调
     */
    const cancelHandler = () => {
      reject(new Error('取消'))
    }

    /**
     * 确定回调
     */
    const confirmHandler = () => {
      resolve()
    }

    const vnode = h(confirmComponent, {
      title,
      content,
      cancelText,
      confirmText,
      close,
      cancelHandler,
      confirmHandler
    })
    // 渲染
    render(vnode, document.body)
  })
}